<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no" />
  <title>声音播放</title>
  <script type="text/javascript" src="static/js/jquery.js"></script>
  <script type="text/javascript" src="static/js/socket.io.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      var sleep = time=>new Promise(resolve=>setTimeout(resolve,time));
      var voice_array = [];
      // var socket = io('http://lzweb.dwtv.tv:3041');
      var socket = io('http://localhost:3041');
      socket.on('connect', function(){
          console.log(4001);
      });
      socket.on('m:answer', function(data){
        console.log("message is coming, the content is "+JSON.stringify(data));
        if(data.force_play && data.is_playing){
          let file_path = $("#player").attr("src");
          if(file_path!="" && file_path!='undefined'){
            socket.emit("m:delete_voice",file_path)
          }
          if(voice_array.length>0){
            socket.emit("m:delete_voice",voice_array.shift())
          }
        }
        if(!!data.message_path){
          voice_array.push(data.message_path);
        }
        voice_array.push(data.filepath);
        let path_temp = voice_array.shift();
        $("#player").attr("src",path_temp)
        var player = $("#player")[0];
        player.play();
        
        //下面是log
        let template = '';
        if(data.need_turing == "1"){
          template = `<p>消息:${data.message}</p><p>回答:${data.answer}</p>`
        }else{
          template = `<p>不过图灵的消息:${data.message}</p>`
        }
        $("#log").prepend(template);
      });
      socket.on('m:error', function(data){
        let template = `<p>${data.message} 原回答是：${data.answer}</p>`
        $("#log").prepend(template);
      });
      socket.on('disconnect', function(){});
      
      $("#player")[0].addEventListener('ended',async function () {  
        let file_path = $("#player").attr("src");
        if(voice_array.length>0){
          socket.emit("m:delete_voice",file_path);
          await sleep(1500);
          $("#player").attr("src",voice_array.shift());
          var player = $("#player")[0];
          player.play();
        }else{
          $("#player").attr("src","");
          socket.emit("m:delete_voice",file_path)
          // socket.emit("m:play_finished")
        }
      }, false);
    });
   </script>
</head>
<body>
    <audio id="player" src="" controls></audio>
    <div id="log" style="overflow: scroll;height: 500px;">
      
    </div>
</body>
</html>


